package cn.cheneyjoo.sqlsession;

import cn.cheneyjoo.config.MySqlSessionProxy;
import cn.cheneyjoo.model.Configuration;
import cn.cheneyjoo.model.MappedStatement;

import java.lang.reflect.*;
import java.util.List;
import java.util.Locale;

public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        SimpleExecutor executor = new SimpleExecutor();
        List<Object> objects = executor.query(configuration, configuration.getMappedStatementMap().get(statementId), params);
        return (List<E>) objects;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> objects = selectList(statementId, params);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        } else {
            throw new RuntimeException("查询结果为空或者查询到多个对象");
        }
    }

    @Override
    public int insert(String statementId, Object... params) throws Exception {
        SimpleExecutor executor = new SimpleExecutor();
        return executor.update(configuration, configuration.getMappedStatementMap().get(statementId), params);
    }

    @Override
    public int update(String statementId, Object... params) throws Exception {
        SimpleExecutor executor = new SimpleExecutor();
        return executor.update(configuration, configuration.getMappedStatementMap().get(statementId), params);
    }

    @Override
    public int delete(String statementId, Object... params) throws Exception {
        SimpleExecutor executor = new SimpleExecutor();
        return executor.update(configuration, configuration.getMappedStatementMap().get(statementId), params);
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new MySqlSessionProxy(configuration,this));
        return (T) proxyInstance;
    }
}
